import { defineStore } from "pinia";
import { GetUserInfo } from "@/services/user";
import { getMenuList, getUserInfo } from "@/services/mock";
import router from "@/router";
import useTagsViewStore from "./tagsView";
import { generatorDynamicRouter } from "@/utils/generator-routers";
import { useSocketStore } from "./socket";

//格式化接口返回的菜单，不是菜单的不在左侧菜单展示
const formatMenu = (arr, list = []) => {
    arr.map((v) => {
        if (!v.isMenu) return;
        let _obj = {
            label: v.title,
            key: v.name,
            iconName: v.iconName,
            path: v.path,
        };
        if (v.children && v.children.length) {
            let _list = formatMenu(v.children);
            _obj.children = _list;
        }
        list.push(_obj);
    });
    return list;
};

export const useUserStore = defineStore({
    id: "user",
    state: () => ({
        name: "11",
        userInfo: {}, //用户信息
        menuList: [], //菜单列表
        menuData: [],
        authList: ["click1", "click2"], //按钮权限
    }),
    //开启数据缓存
    // persist: {
    //     enabled: true
    // },
    getters: {
        UserInfo() {
            return this.userInfo;
        },

        MenuData() {
            return this.menuData;
        },
    },
    actions: {
        //获取用户信息
        async getUserInfo() {
            // const socketStore = useSocketStore();
            // let res = await GetUserInfo();
            let res = await getUserInfo();
            if (res.code === 200) {
                //登录成功，连接websocket
                // socketStore.connection();
                this.userInfo = res.data;
                let res0 = await getMenuList();
                if (res0.code === 200) {
                    let menuList = formatMenu(res0.data);
                    this.menuData = res0.data;
                    this.menuList = menuList;
                    let _menuList = await generatorDynamicRouter(res0.data);
                    await _menuList.forEach((it) => {
                        router.addRoute(it);
                    });
                    return res0;
                } else {
                    return res0;
                }
            } else {
                return res;
            }
        },

        //退出
        Logout() {
            const tagsViewStore = useTagsViewStore();

            const { fullPath } = router.currentRoute.value;
            this.$patch({
                userInfo: {},
                menuList: [],
                menuData: [],
                authList: [],
            });
            tagsViewStore.clearView();

            localStorage.setItem("Token", null);
            //重定向到登录页
            router.replace({
                name: "login",
                query: {
                    redirect: fullPath ? encodeURIComponent(fullPath) : "",
                },
            });
        },
    },
});
